<?php

namespace App\Pay;

use App\Service\HttpService;
use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;

class Paypal
{


    private $account = 'sb-i7q1f14522069@business.example.com';
    private $clientId = 'AUoC6HcL5r7R2bFjJPRxFU4gBbFJjjeckumVeXWL-h8N8ZlJOCCd-yRhlodmeUmH91a2LY6MXT6bZXHb';
    private $clientSecret = 'EMSUB57Wn1YCHzp78SUNLk4Fqq3475UDT9RtGe_CKNfPBNRs2mGaMf8DyfH-RG0LaIGRF1EOblXu_mdq';
    private $url = 'https://api-m.sandbox.paypal.com';
    private $token;

    /**
     * @Inject()
     * @var HttpService
     */
    private $httpService;


    public function __construct()
    {

        $token = redis()->get('paypal-token');
        if (empty($token)) {
            $token = $this->getToken();
        }

        $this->token = $token;

    }


    public function test()
    {
        var_dump(123123);
    }


    /**
     * PayPal 支付创建订单
     * @param $param
     * @return false|ResponseInterface
     */
    public function createOrder($param)
    {
        $options = [];
        $options['auth'] = [$this->clientId, $this->clientSecret];
        $options['headers'] = [
            'Content-Type' => 'application/json',
            'Authorization' => ' Bearer ' . $this->token,
        ];

        $json = [];

        //todo 商品详情参数现在不传 上线验证能否通过风控
        $json['intent'] = 'CAPTURE';
        $json['purchase_units'] = [[
            'amount' => [
                'currency_code' => 'USD',
                'value' => $param['price'],
                'breakdown' => [
                    'item_total' => [
                        'currency_code' => 'USD',
                        'value' => $param['price']
                    ]
                ]
            ],
            'reference_id' => $param['order_no'],
            'description' => $param['descriptor']
        ]];

        $json['application_context'] = [
            'return_url' => "https://www.aroundseeking.com",
            'cancel_url' => "https://www.baidu.com",
        ];


        $options['json'] = $json;

        $url = $this->url . '/v2/checkout/orders';

        return $this->httpService->request($url, $options, 'POST');

    }


    /**
     * 查询订单状态 返回 订单状态
     * @param $id
     * @return bool|ResponseInterface
     */
    public function findOrder($id)
    {

        $options = [];
        $options['auth'] = [$this->clientId, $this->clientSecret];
        $options['headers'] = [
            'Content-Type' => 'application/json',
            'Authorization' => ' Bearer ' . $this->token,
        ];
        $url = $this->url . '/v2/checkout/orders/' . $id;

        $result = $this->httpService->request($url, $options);

        // status  COMPLETED 成功  APPROVED 已授权
        if (is_array($result) && isExistence($result, ['id', 'status'])) {

            //在是授权的时候进行扣款操作
            if ($result['status'] == 'APPROVED') {
                return $this->captureOrder($id);
            } else {
                return $result;
            }
        } else {
            return false;
        }
    }


    /**
     * paypal 扣款操作
     * @param $id
     * @return false|ResponseInterface
     */
    public function captureOrder($id)
    {

        $options = [];
        $options['auth'] = [$this->clientId, $this->clientSecret];
        $options['headers'] = [
            'Content-Type' => 'application/json',
            'Authorization' => ' Bearer ' . $this->token,
        ];

        $url = $this->url . '/v2/checkout/orders/' . $id . '/capture';

        return $this->httpService->request($url, $options, 'POST');

    }


    public function subscribeCaptureOrder($id,$price){
        $options = [];
        $options['headers'] = [
            'Content-Type' => 'application/json',
            'Authorization' => ' Bearer ' . $this->token,
        ];

        $options['json'] = [
            'amount'=>[
                'currency_code'=>'USD',
                'value'=>$price,
            ],
            'capture_type'=>'OUTSTANDING_BALANCE',
            'note'=>'Charging as the balance reached the limit'
        ];



        $url = $this->url . '/v1/billing/subscriptions/' . $id . '/capture';

        return $this->httpService->request($url, $options, 'POST');

    }




    public function subscribePlans($productId)
    {

        $options = [];
        $options['headers'] = $this->commonJsonHeader();

        $options['query'] = [
            'product_id' => $productId
        ];


        $url = $this->url . '/v1/billing/plans';
        $this->httpService->request($url, $options);

    }


    /**
     * 创建产品
     * @return false|ResponseInterface
     */
    public function createProduct()
    {
        $options = [];
        $options['headers'] = $this->commonJsonHeader();
        $options['json'] = [
            'name' => 'SeekingAround',
            'description' => 'Automatic subscription renewal for user membership',
            'type' => 'SERVICE',
            'category' => 'ONLINE_DATING',
            'image_url' => 'https://www.aroundseeking.com/_nuxt/logo.e5dc2d7c.png',
            'home_url' => 'https://www.aroundseeking.com/',
        ];

        $url = $this->url . '/v1/catalogs/products';

        $result = $this->httpService->request($url, $options, 'POST');

        logger()->info('生成PayPal产品', $result);


        return $result;


    }


    /**
     * 生成订阅计划
     * @param $data
     * @return false|ResponseInterface
     */
    public function createPlan($data)
    {

        $options = [];
        $options['headers'] = $this->commonJsonHeader();

        $options['json'] = [
            'product_id' => 'PROD-03T08498PB515971G',
            'name' => $data['name'],
            'description' => $data['title'],
            'status' => 'ACTIVE',
            'billing_cycles' => [
//                [
//                    'frequency' => [
//                        'interval_unit' => 'DAY',
//                        'interval_count' => $data['term']
//                    ],
//                    'tenure_type' => 'TRIAL',
//                    'sequence' => 1,
//                    'total_cycles' => 1,
//                    'pricing_scheme' => [
//                        'fixed_price' => [
//                            'value' =>'8',
//                            'currency_code' => 'USD'
//                        ]
//                    ]
//                ],
                [
                    'frequency' => [
                        'interval_unit' => 'DAY',
                        'interval_count' => $data['term']
                    ],
                    'tenure_type' => 'REGULAR',
                    'sequence' => 1,
                    'total_cycles' => 0,
                    'pricing_scheme' => [
                        'fixed_price' => [
                            'value' => $data['price'],
                            'currency_code' => 'USD'
                        ]
                    ]
                ]

            ],
            'payment_preferences' => [
                'auto_bill_outstanding' => true,// 自动续费
                'payment_failure_threshold' => 3,//订阅付费 重试次数
                'setup_fee' => [
                    'value' => 7,
                    'currency_code' => 'USD',
                    'setup_fee_failure_action' => 'CANCEL'
                ]
            ],
            'taxes' => [ // todo 税收部分上线具体问财务
                'percentage' => '1',
                'inclusive' => true
            ]
        ];

        $url = $this->url . '/v1/billing/plans';
        $result = $this->httpService->request($url, $options, 'POST');
        var_dump($result);
        logger()->info('生成PayPal计划订阅', [$result]);

        return $result;

    }


    public function createSubscriptions($data)
    {
        $options = [];
        $options['headers'] = $this->commonJsonHeader();

        $options['json'] = [
            'plan_id' => $data['plan_id'],
            'start_time' => str_replace('+00:00', 'Z', gmdate('c',time()+86400)),
//            'shipping_amount' => [
//                'currency_code' => 'USD',
//                'value' => $data['price']
//            ],
            'application_context' => [
                'brand_name' => 'walmart',
                'locale' => 'en-US',
                'shipping_preference' => 'NO_SHIPPING',
                'user_action' => 'SUBSCRIBE_NOW',
                'payment_method' => [
                    'payer_selected' => 'PAYPAL',
                    'payee_preferred' => 'IMMEDIATE_PAYMENT_REQUIRED'
                ],
                'return_url' => env('WEB_URL') . '/paying/result',
                'cancel_url' => env('WEB_URL') . '/paying/result?orderType=cancel',
            ]

        ];

        var_dump($options);
        $url = $this->url . '/v1/billing/subscriptions';
        $result = $this->httpService->request($url, $options, 'POST');


        return $result;
    }


    public function subscriptions($id,$price)
    {

        $options = [];
        $options['headers'] = $this->commonJsonHeader();


        $url = $this->url . '/v1/billing/subscriptions/' . $id;

        $result = $this->httpService->request($url, $options);

        logger()->info('subscriptions',[$result]);

//        if (is_array($result) && isExistence($result, ['id', 'status'])) {
//
//
//            /*
//             * APPROVAL_PENDING. 订阅已创建但尚未获得买家批准。
//                APPROVED. 买方已批准订阅。
//                ACTIVE. 订阅有效。
//                SUSPENDED. 订阅已暂停。
//                CANCELLED. 订阅被取消。
//                EXPIRED. 订阅已过期。
//             */
//            // 用户已经授权进行扣款
//            if ($result['status'] == 'ACTIVE') {
//
//                $ss = $this->subscribeCaptureOrder($id,$price);
//                var_dump($ss);
//                var_dump(121);
//               return $ss;
//
//            }
//
//
//        }
//
//
        return $result;


    }


    public function transactions($id){
        $options = [];
        $options['headers'] = $this->commonJsonHeader();
        $options['query'] = [
            'start_time'=>'2023-03-19T00:00:00.940Z',
            'end_time'=>'2023-03-21T11:00:00.940Z',
        ];

        $url = $this->url . '/v1/billing/subscriptions/' . $id.'/transactions';

        $result = $this->httpService->request($url, $options);
        var_dump($result);
        return $result;
    }










    /**
     * 通用的header 设置
     * @return string[]
     */
    public function commonJsonHeader(): array
    {
        return [
            'Content-Type' => 'application/json',
            'Authorization' => ' Bearer ' . $this->token,
        ];
    }


    /**
     * 获取token
     * @return string|bool
     */
    public function getToken()
    {

        $options = [];
        $options['auth'] = [$this->clientId, $this->clientSecret];
        $options['headers'] = [
            'Content-Type' => 'application/x-www-form-urlencoded'
        ];
        $options['form_params'] = [
            'grant_type' => "client_credentials"
        ];

        $url = $this->url . '/v1/oauth2/token';

        $result = $this->httpService->request($url, $options, 'POST');

        if ($result) {
            redis()->set('paypal-token', $result['access_token'], $result['expires_in']);
            return $result['access_token'];
        } else {
            return false;
        }

    }


}
